package com.mdinic.blogovi.ctrl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.mdinic.blogovi.model.BlogPost;
import com.mdinic.blogovi.model.Person;
import com.mdinic.blogovi.model.Share;

@RequestMapping("/shares")
@Controller
@RooWebScaffold(path = "shares", formBackingObject = Share.class)
@RooWebFinder
public class ShareController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Share share, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, share);
            return "shares/create";
        }
        uiModel.asMap().clear();
        share.persist();
        return "redirect:/shares/" + encodeUrlPathSegment(share.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Share());
        List<String[]> dependencies = new ArrayList<String[]>();
        if (BlogPost.countBlogPosts() == 0) {
            dependencies.add(new String[] { "blogpost", "blogposts" });
        }
        if (Person.countPeople() == 0) {
            dependencies.add(new String[] { "person", "people" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "shares/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("share", Share.findShare(id));
        uiModel.addAttribute("itemId", id);
        return "shares/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("shares", Share.findShareEntries(firstResult, sizeNo));
            float nrOfPages = (float) Share.countShares() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
                    : nrOfPages));
        } else {
            uiModel.addAttribute("shares", Share.findAllShares());
        }
        return "shares/list";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Share share, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, share);
            return "shares/update";
        }
        uiModel.asMap().clear();
        share.merge();
        return "redirect:/shares/" + encodeUrlPathSegment(share.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Share.findShare(id));
        return "shares/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Share share = Share.findShare(id);
        share.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/shares";
    }

    void populateEditForm(Model uiModel, Share share) {
        uiModel.addAttribute("share", share);
        uiModel.addAttribute("blogposts", BlogPost.findAllBlogPosts());
        uiModel.addAttribute("people", Person.findAllPeople());
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }

	@RequestMapping(params = { "find=ByBlogPost", "form" }, method = RequestMethod.GET)
    public String findSharesByBlogPostForm(Model uiModel) {
        uiModel.addAttribute("blogposts", BlogPost.findAllBlogPosts());
        return "shares/findSharesByBlogPost";
    }

	@RequestMapping(params = "find=ByBlogPost", method = RequestMethod.GET)
    public String findSharesByBlogPost(@RequestParam("blogPost") BlogPost blogPost, Model uiModel) {
        uiModel.addAttribute("shares", Share.findSharesByBlogPost(blogPost).getResultList());
        return "shares/list";
    }

	@RequestMapping(params = { "find=ByPerson", "form" }, method = RequestMethod.GET)
    public String findSharesByPersonForm(Model uiModel) {
        uiModel.addAttribute("people", Person.findAllPeople());
        return "shares/findSharesByPerson";
    }

	@RequestMapping(params = "find=ByPerson", method = RequestMethod.GET)
    public String findSharesByPerson(@RequestParam("person") Person person, Model uiModel) {
        uiModel.addAttribute("shares", Share.findSharesByPerson(person).getResultList());
        return "shares/list";
    }
}
